package com.yonyou.pmclouds.basecom.bp.template;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public abstract class SingleOperateBpTemplate<T> {
    protected List<SingleProcessor<T>> beforeProcessor = new ArrayList<>();
    protected List<SingleProcessor<T>> afterProcessor = new ArrayList<>();

    protected abstract void operateDirect(T vo, T orig);

    protected T getOrigVO(T vo) throws BusinessException {
        return null;
    }

    protected void before(T vo, T orig) throws BusinessException {
        for (int i = 0; i < beforeProcessor.size(); i++) {
            beforeProcessor.get(i).process(vo, orig);
        }
    }

    protected void after(T vo, T orig) throws BusinessException {
        for (int i = 0; i < afterProcessor.size(); i++) {
            afterProcessor.get(i).process(vo, orig);
        }
    }

    public SingleOperateBpTemplate addBeforeProcessor(SingleProcessor<T> processor) {
        beforeProcessor.add(processor);
        return this;
    }


    public SingleOperateBpTemplate addAfterProcessor(SingleProcessor<T> processor) {
        afterProcessor.add(processor);
        return this;
    }

    protected T execute(T vo) throws BusinessException {
        try {
            T orig = getOrigVO(vo);
            before(vo, orig);
            operateDirect(vo, orig);
            after(vo, orig);
        } catch (PersistenceException ex) {
            log.error("查询数据发生错误", ex);
            throw new BusinessException("查询数据发生错误!");
        }
        return vo;
    }

}
